/**
 * 
 */
package com.alstudio.ui.module.voip;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alstudio.utils.android.device.ALDisplayMetricsManager;
import com.alstudio.utils.log.ALLog;
import com.loovee.imaohu.R;

/**
 * @author alonso lee
 * 
 */
public class MeteorView extends FrameLayout {

	private ArrayList<ImageView> meteors = new ArrayList<ImageView>();

	private HashMap<Integer, Bitmap> bitmapMap = new HashMap<Integer, Bitmap>();

	private Context mContext;

	private Bitmap meteorImg;

	private int numMeteors = 0;

	/**
	 * @param context
	 */
	public MeteorView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.mContext = context;
		meteorImg = BitmapFactory.decodeResource(getResources(),
				R.drawable.meet_flash_meteoric_01);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		// TODO Auto-generated method stub
		super.onSizeChanged(w, h, oldw, oldh);
	}

	public void addMeteor(int num) {
		for (int i = 0; i < num; ++i) {
			ImageView child = createMeteors(meteorImg);
//			child.setAnimation(getMeteorFlyAnimationSet());
			meteors.add(child);
			addView(child, getLayoutParamsForMeterLight());
		}
	}

	public void resume() {
		for (ImageView child : meteors) {
			child.startAnimation(getMeteorFlyAnimationSet());
		}
	}

	public void pause() {
		for (ImageView child : meteors) {
			child.clearAnimation();
		}
	}

	public void destroy() {
		new Thread() {
			public void run() {
				meteors.clear();
				for (Entry<Integer, Bitmap> entry : bitmapMap.entrySet()) {
					Bitmap value = entry.getValue();
					int key = entry.getKey();
					if (value != null && !value.isRecycled()) {
						value.recycle();
						value = null;
						ALLog.d("销毁 " + key);
					}
				}
				bitmapMap.clear();
				bitmapMap = null;
				meteors = null;
				if (meteorImg != null && !meteorImg.isRecycled()) {
					meteorImg.recycle();
					meteorImg = null;
				}
				ALLog.d(getClass().getSimpleName()+" 销毁完毕 ");
			};
		}.start();
	}

	private FrameLayout.LayoutParams getLayoutParamsForMeterLight() {

		FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		Random random = new Random();// 指定种子数字

		int marginTop = 0;
		int marginBottom = 0;
		int divisor = random.nextInt(5) + 1;
		int leftOrRight = random.nextInt(2);
		switch (leftOrRight) {
		case 0:
			p.gravity = Gravity.LEFT;
			marginTop = random.nextInt(ALDisplayMetricsManager
					.getScreenHeight(mContext) / divisor);
			break;
		case 1:
			p.gravity = Gravity.CENTER_HORIZONTAL;
			marginTop = random.nextInt(ALDisplayMetricsManager
					.getScreenHeight(mContext) / divisor);

			break;
		case 2:
			p.gravity = Gravity.RIGHT;
			marginTop = random.nextInt(ALDisplayMetricsManager
					.getScreenHeight(mContext) / divisor);
			break;
		case 3:
			p.gravity = Gravity.BOTTOM;
			marginBottom = random.nextInt(ALDisplayMetricsManager
					.getScreenHeight(mContext) / divisor);
			break;
		}

		leftOrRight = random.nextInt(ALDisplayMetricsManager
				.getScreenWidth(mContext) / 2);

		p.setMargins(leftOrRight, marginTop, 0, marginBottom);

		return p;
	}

	private ImageView createMeteors(Bitmap originalBitmap) {
		Flake flake = new Flake();
		// Size each flake with a width between 5 and 55 and a proportional
		// height

		if (flake.width >= originalBitmap.getWidth()) {
			flake.width = originalBitmap.getWidth();
		}

		flake.width = (int) (5 + (float) Math.random() * 50);
		float hwRatio = originalBitmap.getHeight() / originalBitmap.getWidth();
		if (hwRatio == 0) {
			hwRatio = originalBitmap.getWidth() / originalBitmap.getHeight();
		}
		flake.height = (int) (flake.width * hwRatio);

		// Position the flake horizontally between the left and right of the
		// range
		flake.x = (float) Math.random() * (-flake.width);
		// Position the flake vertically slightly off the top of the display
		flake.y = 0 - (flake.height + (float) Math.random() * flake.height);

		// Each flake travels at 50-200 pixels per second
		flake.speed = 150 + (float) Math.random() * 150;

		flake.rotation = 0;
		flake.rotationSpeed = 0;

		// Get the cached bitmap for this size if it exists, otherwise create
		// and cache one
		flake.bitmap = bitmapMap.get(flake.width);
		if (flake.bitmap == null) {
			flake.bitmap = Bitmap.createScaledBitmap(originalBitmap,
					(int) flake.width, (int) flake.height, true);
			bitmapMap.put(flake.width, flake.bitmap);
		}

		ImageView img = new ImageView(mContext);
		img.setImageBitmap(flake.bitmap);
		return img;
	}

	/**
	 * 流星雨夜扫把飞的set
	 * 
	 * @param isNeedTrans
	 * @param isUp
	 * @return
	 */
	private AnimationSet getMeteorFlyAnimationSet() {
		AnimationSet set = new AnimationSet(true);

		Random random = new Random();// 指定种子数字

		long duration = 1000;

		duration = (random.nextInt(8) + 12) * 500;
		TranslateAnimation down = null;

		down = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0,
				Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT,
				-0.1f, Animation.RELATIVE_TO_PARENT, 1.0f);
		down.setDuration(duration);
		down.setRepeatCount(Animation.INFINITE);
		down.setRepeatMode(Animation.RESTART);

		TranslateAnimation turn = null;

		turn = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 1.0f,
				Animation.RELATIVE_TO_PARENT, -1.0f - 0.5f,
				Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT,
				0);

		set.addAnimation(down);

		random = new Random();// 指定种子数字

		down.setStartOffset((1 + random.nextInt(3)) * 500);

		random = new Random();// 指定种子数字
		turn.setStartOffset(Math.abs((3 + random.nextInt(4)) * 500));
		turn.setDuration(Math.abs(duration - turn.getStartOffset()));
		turn.setRepeatCount(Animation.INFINITE);
		turn.setRepeatMode(Animation.RESTART);

		set.addAnimation(turn);

		LinearInterpolator lir = new LinearInterpolator();
		set.setInterpolator(lir);

		return set;
	}

}
